# -*- coding: utf-8 -*-
import os
import re
import urllib

from django.conf import settings
from django.shortcuts import *
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.template import RequestContext
from django import newforms as forms
from django.utils.encoding import smart_str
from django.views.decorators import cache

import utils
from models import Document

def get_command(req):
    if 'edit' in req.REQUEST:
        return 'edit', False
    elif 'diff' in req.REQUEST:
        return 'diff', False
    elif 'raw' in req.REQUEST:
        return 'raw', False
    elif 'delete' in req.REQUEST:
        return 'delete', False
    elif 'new' in req.REQUEST:
        return 'new', False
    elif 'attach' in req.REQUEST:
        return 'attach', False
    else:
        return 'show', False

def show(req, word):
    doc = Document(word or settings.WIKI_HOME)
    if doc.filename.endswith('/'):
        # Strip the last slash
        return HttpResponseRedirect(re.sub(r'^(.*?)/+$', r'\1', doc.get_absolute_url()))

    if doc.data is None:
        return _edit(req, doc)

    cmd, login_required = get_command(req)
    if login_required and not req.user.is_authenticated():
        # Not implemented
        raise Http404

    response = globals()['_%s' % cmd](req, doc)
    return response

def _raw(req, doc):
    return HttpResponse(doc.data, mimetype=doc.mimetype)

def _show(req, doc):
    if doc.is_image():
        template_name = 'image.html'
    elif doc.is_binary():
        template_name = 'binary.html'
    else:
        template_name = 'document.html'
    return render_to_response('wiki/%s' % template_name,
                              {'document': doc,
                               },
                              context_instance=RequestContext(req))

class NewDocumentForm(forms.Form):
    word = forms.CharField()

def _new(req, doc):
    form = NewDocumentForm(req.POST or None)
    if form.is_valid():
        new_doc = Document(form.clean()['word'])
        return HttpResponseRedirect('%s?edit' % new_doc.get_absolute_url())
    return render_to_response('wiki/new_document.html',
                              {'form': form},
                              context_instance=RequestContext(req),
                              )

class DocumentForm(forms.Form):
    content = forms.CharField(widget=forms.Textarea())

def _edit(req, doc):
    if doc.is_binary():
        return HttpResponseRedirect(doc.get_absolute_url())

    if req.method != 'POST':
        form = DocumentForm(initial=dict(content=doc.data))
    else:
        form = DocumentForm(req.POST or None)
        if form.is_valid():
            data = form.clean()
            doc.write(smart_str(data['content']),
                      username=None,
                      description=None)
            return HttpResponseRedirect(doc.get_absolute_url())

    return render_to_response('wiki/form.html',
                              {'form': form,
                               'doc' : doc,
                               },
                              context_instance=RequestContext(req),
                              )

def _delete(req, doc):
    if req.method == 'POST':
        doc.remove()
        return HttpResponseRedirect('/')
    return render_to_response('wiki/delete_confirm.html',
                              {'document': doc },
                              context_instance=RequestContext(req),
                              )

def _diff(req, doc):
    if doc.is_binary():
        return HttpResponseRedirect(doc.get_absolute_url())

    from difflib import Differ
    d = Differ()
    data1 = doc.read(revision=-1).splitlines(1)
    data2 = doc.data.splitlines(1)
    diff = d.compare(data1, data2)

    return render_to_response('wiki/diff.html',
                              {'diff'    : diff,
                               },
                              context_instance=RequestContext(req),
                              )

class AttachForm(forms.Form):
    attachment = forms.FileField()

def _attach(req, doc):
    form = AttachForm(req.POST or None, req.FILES or None)
    if form.is_valid():
        attachment = form.clean()['attachment']
        new_doc = Document(os.path.join(doc.parent_dir, attachment.filename))
        new_doc.write(attachment.content)
        return HttpResponseRedirect(new_doc.get_absolute_url())

    return render_to_response('wiki/attach.html',
                              {'form': form,
                               },
                              context_instance=RequestContext(req),
                              )
